<template>
    <div class="dashboard-list-container">
        <global-search @submitSearch="submitSearch" :showDep="false" class="global-tool-search">
            <template slot="other-form">
                <el-form-item label="检索">
                    <el-input v-model="form.keyword" clearable placeholder="请输入文件名搜索"></el-input>
                </el-form-item>
            </template>
            <template slot="tool-box">
                <el-button type="text" icon="el-icon-upload2" v-auth="{code: 200002000001}" @click="showDialog">上传
                </el-button>
                <el-button type="text" @click="toExport" v-auth="{code: 200002000002}">
                    <svg-icon icon-class="export"/>
                    导出
                </el-button>
            </template>
        </global-search>
        <div class="tables-box">
            <el-table
                border
                :data="tableData"
                :max-height="tableHeight"
                tooltip-effect="light"
                row-key="packageID"
                style="width: 100%"
                :empty-text="emptyText"
                @sort-change="sortChange"
                @selection-change="handleSelectionChange">
                <el-table-column
                    show-overflow-tooltip
                    fixed
                    type="selection"
                    :reserve-selection="true"
                    align="center"
                    width="30">
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    fixed
                    prop="date"
                    align="center"
                    type="index"
                    label="序号"
                    width="40">
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    prop="fileName"
                    align="left"
                    label="文件名"
                    min-width="150">
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    prop="totalCase"
                    align="center"
                    sortable="custom"
                    label="病案数"
                    min-width="100">
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    prop="group"
                    align="center"
                    sortable="custom"
                    label="入组病案"
                    min-width="80">
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    prop="ungroup"
                    align="center"
                    sortable="custom"
                    label="未入组病案"
                    min-width="90">
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    prop="excluded"
                    align="center"
                    sortable="custom"
                    label="排除组病案"
                    min-width="100">
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    prop="uploadDate"
                    align="center"
                    sortable="custom"
                    label="上传时间"
                    min-width="150">
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    prop="uploadPerson"
                    align="center"
                    sortable="custom"
                    label="上传人"
                    min-width="70">
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    prop="explanation"
                    align="left"
                    label="提示"
                    min-width="100">
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    prop="uploadState"
                    align="center"
                    sortable="custom"
                    label="状态"
                    min-width="65"
                    fixed="right">
                    <template slot-scope="scope">
                        <el-progress v-if="scope.row.uploadState === 1 || scope.row.uploadState === 3"
                                     :text-inside="true" :stroke-width="16"
                                     :percentage="scope.row.progrossValue"></el-progress>
                        <span v-else :class="{
                                'status-yellow': scope.row.uploadState === 1 || scope.row.uploadState === 3,
                                'status-green': scope.row.uploadState === 2,
                                'status-red': scope.row.uploadState === 0}">
                                    {{scope.row.uploadState | getState}}
                                </span>
                    </template>
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    label="操作"
                    align="center"
                    min-width="160"
                    fixed="right">
                    <template slot-scope="scope">
                        <el-button type="text" v-if="!scope.row.uploadState" @click="toGroup(scope.row)">分组</el-button>
                        <el-button type="text" @click="showDialog(scope.$index, scope.row)">重新导入</el-button>
                        <el-button type="text" v-if="scope.row.status === '1' || isSystemUser" @click="deleteRow(scope.$index, scope.row)">删除</el-button>
                        <el-button type="text" @click="toPackage(scope.row)">查看</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="tableData.length > 0" :total="total" :page.sync="currentPage" :limit.sync="pageSize"
                        @pagination="changePage"/>
        </div>
        <el-dialog
            title="导入文件"
            :visible.sync="dialogVisible"
            :close-on-click-modal="false"
            width="30%"
            center
            :before-close="handleClose">
            <div class="content">
                <div class="template-box">
                    <p><i class="el-icon-warning"></i><span>请以卫统4或HQMS标准文件进行上传</span></p>
                    <el-button type="text" size="small" @click="downloadTemplate" icon="el-icon-download">下载模板
                    </el-button>
                </div>
                <upload-file
                    :drag="true"
                    :limit="limit"
                    :isdbf="true"
                    :iscsv="true"
                    accept=".xls,.xlsx,.dbf,.csv"
                    :noPrompt="true"
                    :fileList="fileList"
                    @removeFile="removeFile">
                </upload-file>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleClose">取 消</el-button>
                <el-button type="primary" @click="submitFileList">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import {getMRpackage, removePackage, exportPackageList, reQCDataPackage} from '@/api/data-mangement/list'
    import {getSortString, viewInfoMonth, getMoneyNum} from '@/utils/filters'
    import {uploadMultipleFiles, uploadSingleFile} from '@/api/data-mangement/package'
    import {getOverviewAllList} from '@/api/overview/list'
    import uploadFile from '@/components/Upload'
    import * as signalR from '@microsoft/signalr'
    import FileSaver from 'file-saver'
    import ExcelJS from 'exceljs'

    export default {
        name: 'index',
        data () {
            return {
                // 搜索条件
                form: {
                    keyword: ''
                },
                // 当前标签页
                activeName: 'list',
                // 当前页
                currentPage: 1,
                // 每页数量
                pageSize: 20,
                // 表格高度
                tableHeight: 0,
                // 数据总数
                total: 0,
                // 全部表格数据
                tableData: [],
                // 全局搜索内容，用于翻页等不传参时使用数据
                globalForm: {},
                // 选中的数据
                multipleSelection: [],
                // 显示弹框
                dialogVisible: false,
                // 最大上传数
                limit: 5,
                // 文件列表
                fileList: [],
                // 上传数据id
                fileDataId: '',
                // 排序字段
                sortMap: {},
                // 排序方式
                sortType: '',
                // 输入提示
                placeholder: '请输入文件名搜索',
                // 空数据时显示的文本内容
                emptyText: '暂无数据',
                // 是否限制部分表格数据
                showtableCol: false,
                // 使用储存的数据，不去请求
                useStore: false,
                // 连接srg
                connection: null,
                // 导出的全部数据
                allexportData: [],
                // 是否是系统机构
                isSystemUser: false
            }
        },
        created () {
            // tags判断入口是否从选项卡进入
            this.useStore = this.$route.query.tags === 'tags'
            this.initPage()
            this.joinSRG()
            // 头部40 + 快捷标签30 + 面包屑30 + 搜索框42 + tabs高度34 + 分页64 + 底部padding10
            let height = document.documentElement.clientHeight - 100 - 42 - 10 - 64 - 10
            this.tableHeight = height > 108 ? height : 108
            this.isSystemUser = this.getLocalStorage('userMechanism', 'name') === '系统机构'
        },
        mounted () {
            let searchHeight = document.getElementsByClassName('global-tool-search')[0].offsetHeight
            if (searchHeight > 42) {
                let height = document.documentElement.clientHeight - 100 - searchHeight - 10 - 64 - 10
                this.tableHeight = height > 108 ? height : 108
            }
            // 白色背景高度
            document.getElementsByClassName('tables-box')[0].style.height = this.tableHeight + 10 + 64 + 'px'
            // 分页组件位置，不能使用bottom = 0，当位置发生变化时会出错
            document.getElementsByClassName('pagination-container')[0].style.top = this.tableHeight + 10 + 'px'
            window.onresize = () => {
                let height = document.documentElement.clientHeight - 100 - searchHeight - 10 - 64 - 10
                this.tableHeight = height > 108 ? height : 108
                document.getElementsByClassName('tables-box')[0].style.height = this.tableHeight + 10 + 64 + 'px'
                document.getElementsByClassName('pagination-container')[0].style.top = this.tableHeight + 10 + 'px'
            }
        },
        methods: {
            viewInfoMonth,
            /**
             * 连接srg
             */
            joinSRG () {
                let hubUrl = window.location.href.includes('localhost') ? 'http://192.168.0.50/mc/commandhub' : '/mc/commandhub'
                let connection = new signalR.HubConnectionBuilder().withAutomaticReconnect().withUrl(hubUrl).build()
                connection.start().catch()
                connection.on('broadcast', (msg) => {
                    let kind = msg.kind
                    let body = JSON.parse(msg.body)
                    if (kind === 1) {
                        this.tableData.forEach(item => {
                            if (item.packageID === body.packageID) {
                                item.fileName = body.pack.fileName
                                item.totalCase = body.pack.totalCase
                                item.group = body.pack.group
                                item.ungroup = body.pack.ungroup
                                item.excluded = body.pack.excluded
                                item.multi = body.pack.multi
                                item.uploadDate = body.pack.uploadDate
                                item.uploadPerson = body.pack.uploadPerson
                                item.explanation = body.pack.explanation
                                item.uploadState = body.pack.uploadState
                                item.progrossValue = body.progressBar
                            }
                        })
                    }
                })
            },
            /**
             * 初始化页面参数
             */
            initPage () {
                let query = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                if (query) {
                    this.form.keyword = query.keyword
                    this.currentPage = query.pageIndex || 1
                    this.pageSize = query.pageSize || 20
                }
            },
            /**
             * 翻页
             */
            changePage () {
                this.submitSearch()
            },
            /**
             * 提交查询
             * @param form 筛选条件
             */
            submitSearch (form) {
                let data = form || this.globalForm
                this.globalForm = data
                let params = {
                    ...data,
                    state: this.form.state,
                    keyword: this.form.keyword,
                    pageSize: this.pageSize,
                    pageIndex: this.currentPage,
                    orderBy: this.sortType
                }
                this.tableData = []
                this.setGetStore(this.$route.name, params)
                delete params.department
                delete params.depName
                this.getPackageList(params)
            },
            /**
             * 查询数据列表
             * @param params 请求参数
             */
            getList (params) {
                this.emptyText = '加载中...'
                this.showtableCol = params.state !== 2
                if (this.getSession(this.$route.name, 'getOverviewAllList') && this.useStore) {
                    this.useStore = false
                    let res = this.getSession(this.$route.name, 'getOverviewAllList')
                    this.emptyText = '暂无数据'
                    if (res.code.toString() === '200') {
                        this.total = res.data.total
                        this.tableData = res.data.rows
                        this.sortMap = res.data.maps
                    }
                } else {
                    getOverviewAllList(params).then(res => {
                        this.useStore = false
                        this.setSession(this.$route.name, {getOverviewAllList: res})
                        this.emptyText = '暂无数据'
                        if (res.code.toString() === '200') {
                            this.total = res.data.total
                            this.tableData = res.data.rows
                            this.sortMap = res.data.maps
                        }
                    }).catch(() => {
                        this.emptyText = '暂无数据'
                    })
                }
            },
            /**
             * 查询病案包列表
             * @param params 请求参数
             */
            getPackageList (params) {
                this.emptyText = '加载中...'
                if (this.getSession(this.$route.name, 'getMRpackage') && this.useStore) {
                    this.useStore = false
                    let res = this.getSession(this.$route.name, 'getMRpackage')
                    this.emptyText = '暂无数据'
                    if (res.code.toString() === '200') {
                        this.total = res.data.total
                        this.tableData = res.data.rows
                        this.sortMap = res.data.maps
                    }
                } else {
                    getMRpackage(params).then(res => {
                        this.useStore = false
                        this.setSession(this.$route.name, {getMRpackage: res})
                        this.emptyText = '暂无数据'
                        if (res.code.toString() === '200') {
                            this.total = res.data.total
                            this.tableData = res.data.rows
                            this.sortMap = res.data.maps
                        }
                    }).catch(() => {
                        this.emptyText = '暂无数据'
                    })
                }
            },
            /**
             * 删除数据
             * @param index 索引
             * @param row 行数据
             */
            deleteRow (index, row) {
                let text = `你确定删除病案包"${row.fileName}"文件吗?删除后将不能恢复，请谨慎操作!`
                this.$confirm(text, '删除病案包提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    center: true
                }).then(() => {
                    let params = {
                        id: row.packageID
                    }
                    removePackage(params).then(res => {
                        if (res.code.toString() === '200') {
                            this.$message.success('删除成功!')
                            this.submitSearch()
                        } else {
                            this.$message.error(res.message)
                        }
                    })
                })
            },
            /**
             * 选中事件
             */
            handleSelectionChange (val) {
                this.multipleSelection = val
            },
            /**
             * 获取选中id
             */
            getSelectId () {
                let arr = []
                if (this.multipleSelection.length) {
                    this.multipleSelection.forEach(item => {
                        if (this.activeName === 'package') {
                            arr.push(item.packageID)
                        } else {
                            arr.push(item.medicalRecordID)
                        }
                    })
                    return arr
                } else {
                    return false
                }
            },
            /**
             * 导出病案包
             */
            toExport () {
                let params = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                params.idList = this.getSelectId() || []
                this.$store.dispatch('app/UpdateLoadingText', '0%')
                this.$store.dispatch('app/UpdateIsExport', true)
                this.$store.dispatch('app/UpdateLoading', true)
                params.pageIndex = 1
                params.pageSize = 1000
                this.allexportData = []
                this.sendRequest(params)
            },
            /**
             * 发送请求
             * @param params 请求参数
             */
            sendRequest (params) {
                let allIndex = Math.ceil(this.total / 1000)
                exportPackageList(params).then(res => {
                    if (res.code.toString() === '200') {
                        this.$store.dispatch('app/UpdateLoadingText', parseInt(params.pageIndex / allIndex * 95) + '%')
                        this.allexportData = this.allexportData.concat(res.data)
                        if (params.pageIndex < allIndex) {
                            this.sendRequest({...params, pageIndex: params.pageIndex + 1})
                        } else {
                            this.exportDataList('病案包列表', this.allexportData)
                        }
                    } else {
                        this.$store.dispatch('app/UpdateIsExport', false)
                        this.$store.dispatch('app/UpdateLoading', false)
                        this.$message.error('导出失败')
                    }
                }).catch(() => {
                    this.$store.dispatch('app/UpdateIsExport', false)
                    this.$store.dispatch('app/UpdateLoading', false)
                    this.$message.error('导出失败')
                })
            },
            /**
             * 导出excel表头
             */
            getHeader () {
                return [{
                    header: '序号', key: 'index', width: 10
                }, {
                    header: '文件名', key: 'fileName', width: 48
                }, {
                    header: '病案数', key: 'totalCase', width: 16
                }, {
                    header: '入组病案', key: 'group', width: 16
                }, {
                    header: '未入组病案', key: 'ungroup', width: 16
                }, {
                    header: '排除组病案', key: 'excluded', width: 16
                }, {
                    header: '上传时间', key: 'uploadDate', width: 24
                }, {
                    header: '上传人', key: 'uploadPerson', width: 12
                }, {
                    header: '提示', key: 'explanation', width: 48
                }, {
                    header: '状态', key: 'uploadState', width: 16
                }]
            },
            /**
             * 导出列表excel
             */
            exportDataList (name, data) {
                let workbook = new ExcelJS.Workbook()
                workbook.creator = 'lyliang'
                workbook.views = [{
                    x: 0,
                    y: 0,
                    firstSheet: 0,
                    activeTab: 1,
                    visibility: 'visible'
                }]
                let worksheet = workbook.addWorksheet('Sheet1')
                worksheet.columns = this.getHeader()
                for (let i = 0; i < data.length; i++) {
                    data[i].index = i + 1
                    data[i].uploadState = this.$options.filters['getState'](data[i].uploadState)
                    worksheet.addRow(data[i])
                    worksheet.getRow(i + 1).alignment = {vertical: 'middle', horizontal: 'center'}
                    let rate = parseInt((i + 1) / data.length * 0.03 * 100 + 95) + '%'
                    this.$store.dispatch('app/UpdateLoadingText', rate)
                }
                worksheet.getRow(data.length + 1).alignment = {vertical: 'middle', horizontal: 'center'}
                worksheet.getColumn('fileName').alignment = {wrapText: true, vertical: 'middle', horizontal: 'left'}
                worksheet.getColumn('explanation').alignment = {wrapText: true, vertical: 'middle', horizontal: 'left'}
                workbook.xlsx.writeBuffer().then(data => {
                    this.$store.dispatch('app/UpdateLoadingText', '99%')
                    let blob = new Blob([data], {type: 'EXCEL_TYPE'})
                    FileSaver.saveAs(blob, `${this.parseTime(new Date().getTime())} ${name}.xlsx`)
                    this.$store.dispatch('app/UpdateLoadingText', '100%')
                    this.$store.dispatch('app/UpdateIsExport', false)
                    this.$store.dispatch('app/UpdateLoading', false)
                })
            },
            /**
             * 排序修改
             * @param colData.prop 排序参数
             * @param colData.order 正序倒序 ascending 升序 descending 降序 null 不排序默认
             */
            sortChange (colData) {
                this.sortType = getSortString(colData, this.sortMap)
                this.tableData = []
                this.currentPage = 1
                this.submitSearch()
            },
            /**
             * 显示上传弹框
             * @param index 索引
             * @param row 行数据
             */
            showDialog (index, row) {
                this.limit = row ? 1 : 5
                this.fileDataId = row ? row.packageID : ''
                this.fileList = []
                this.dialogVisible = true
            },
            /**
             * 关闭前
             */
            handleClose () {
                if (this.fileList.length > 0) {
                    this.$confirm('还未上传，是否关闭？')
                        .then(() => {
                            this.closeDialog()
                        })
                        .catch()
                } else {
                    this.closeDialog()
                }
            },
            /**
             * 关闭弹窗
             */
            closeDialog () {
                this.fileList = []
                this.dialogVisible = false
            },
            /**
             * 下载模板
             */
            downloadTemplate () {
                window.location.href = `${process.env.BASE_URL}医保结算结果列表模板文件.xlsx`
            },
            /**
             * 删除文件
             * @param uid 要删除的文件
             */
            removeFile (uid) {
                let index = this.fileList.findIndex(item => {
                    return item.uid === uid
                })
                if (index !== -1) {
                    this.fileList.splice(index, 1)
                }
            },
            /**
             * 提交文件
             */
            submitFileList () {
                let params = new FormData()
                for (let i = 0; i < this.fileList.length; i++) {
                    params.append('file', this.fileList[i].raw, this.fileList[i].raw.name)
                }
                if (this.fileDataId !== '') {
                    params.append('id', this.fileDataId)
                    uploadSingleFile(params).then(res => {
                        if (res.code.toString() === '200') {
                            this.closeDialog()
                            this.submitSearch()
                        } else {
                            this.$message.error(res.message)
                        }
                    })
                } else {
                    uploadMultipleFiles(params).then(res => {
                        if (res.code.toString() === '200') {
                            this.closeDialog()
                            this.submitSearch()
                        } else {
                            this.$message.error(res.message)
                        }
                    })
                }
            },
            /**
             * 前往病案包列表
             * @param row 行数据
             */
            toPackage (row) {
                this.setGetStore('ImportMRListIndexDRG', {packageID: row.packageID})
                this.$router.push({name: 'ImportMRListIndexDRG'})
            },
            /**
             * 重新分组
             * @param row 行数据
             */
            toGroup (row) {
                let params = {
                    MRPackageId: row.packageID
                }
                reQCDataPackage(params).then(res => {
                    if (res.code.toString() === '200') {
                        this.$message.success('操作成功')
                        this.submitSearch()
                    } else {
                        this.$message.error(res.message)
                    }
                })
            }
        },
        components: {
            uploadFile
        },
        filters: {
            getMoneyNum,
            getState (val) {
                switch (val) {
                case 0:
                    return '失败'
                case 1:
                    return '排队中'
                case 2:
                    return '成功'
                case 3:
                    return '分组中'
                }
            },
            getType (val) {
                switch (val) {
                case 0:
                    return '正常'
                case 1:
                    return '低倍率'
                case 2:
                    return '高倍率'
                }
            },
            getRiskLevel (val) {
                switch (val) {
                case 0:
                    return ''
                case 1:
                    return '低'
                case 2:
                    return '中低'
                case 3:
                    return '中高'
                case 4:
                    return '高'
                }
            }
        },
        beforeDestroy () {
            this.connection = null
            window.onresize = null
        }
    }
</script>

<style scoped lang="scss">
    .dashboard-list-container {
        .el-form-item--mini.el-form-item {
            margin-bottom: 10px;
        }
        .form-days {
            position: relative;
            .days {
                width: 100px;
                /deep/ input {
                    padding-right: 28px;
                }
            }
            .unit {
                position: absolute;
                right: 7px;
                top: 5px;
                font-size: 14px;
                color: #3A9BFF;
                line-height: 18px;
            }
        }
        .select-input {
            width: 100px;
        }
        .tables-box {
            background: #fff;
            padding: 10px 10px 0;
            position: relative;
            .pagination-container {
                position: absolute;
                top: 0;
                right: 0;
            }
        }
    }

    /deep/ .el-dialog {
        min-width: 600px;
        .el-dialog__body {
            padding: 10px;
            .content {
                width: 90%;
                margin: 0 auto;
                .template-box {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    margin: 0 auto 20px;
                    background: #e7f8ff;
                    border: 1px solid #91dfff;
                    border-radius: 5px;
                    padding: 0 10px;
                    i {
                        color: #46a6ff;
                    }
                }
            }
        }
        .el-dialog__footer {
            text-align: right;
        }
    }
</style>
